package com.itheima.service.impl;

import com.itheima.Util.TransactionUtil;
import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.factory.MapperFactory;
import com.itheima.service.UserService;
import org.apache.ibatis.session.SqlSession;

import java.util.List;


public class UserServiceImpl implements UserService {

    private UserDao userDao;

    @Override
    public List<User> findAllUserInfo() {
        try (SqlSession sqlSession = MapperFactory.getSqlSession()) {
            UserDao userDao = MapperFactory.getMapper(sqlSession, UserDao.class);
            return userDao.findAllUserInfo();
        }
    }

    @Override
    public void saveUserInfo(User user) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            UserDao userDao = MapperFactory.getMapper(sqlSession, UserDao.class);
            userDao.saveUserInfo(user);
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public User selectUserById(Integer id) {
        try (SqlSession sqlSession = MapperFactory.getSqlSession()) {
            UserDao userDao = MapperFactory.getMapper(sqlSession, UserDao.class);
            return userDao.selectUserById(id);
        }
    }

    @Override
    public void updateUserInfo(User user) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            UserDao userDao = MapperFactory.getMapper(sqlSession, UserDao.class);
            userDao.updateUserInfo(user);
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void deleteUserInfo(Integer id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            UserDao userDao = MapperFactory.getMapper(sqlSession, UserDao.class);
            userDao.deleteUserInfo(id);
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
